package com.example.concurrent;

/**
 * There are two way to create a new Thread.
 * Once using Runnable interface and another by extending Thread class.
 *
 */
public class TwoWayCreateNewThread {

	/**
	 * Implement Runnable
	 * Need to create instance = new Thread(Runnable class);
	 *
	 */
	public static class DemoRunnable implements Runnable {
		Thread t;
		private int number = 0;
		public void setNumber(int number) {
			this.number = number;
		}
		
		@Override
		public void run() {
			try {
				System.out.println("Run DemoRunable");
				for(int i = 0; i < 5; i++) {
					System.out.println(number + i);
					Thread.sleep(50);
				}
			} catch (InterruptedException ex) {
				
			}
		}
		
		public void start() {
			if(t==null) {
				t = new Thread(this);
			}
			t.start();
		}
	}
	
	/**
	 * Extend Thread 
	 *
	 */
	public static class DemoThread extends Thread {
		private int number = 0;
		public void setNumber(int number) {
			this.number = number;
		}
		
		public DemoThread() {
			super();
		}
		public void run() {
			try {
				System.out.println("Run DemoThread");
				for(int i = 0; i < 5; i++) {
					System.out.println(number + i);
					Thread.sleep(50);
				}
			} catch (InterruptedException ex) {
				
			}
		}
	}
	
	public static void main (String[] arg) throws InterruptedException{
		System.out.println("--First Way--");
		DemoRunnable r1 = new DemoRunnable();
		DemoRunnable r2 = new DemoRunnable();
		r1.setNumber(0);
		r1.start();
		r2.setNumber(10);
		r2.start();
		
		Thread.sleep(1000);
		
		System.out.println("--Second Way--");
		DemoThread t1 = new DemoThread();
		DemoThread t2 = new DemoThread();
		t1.setNumber(0);
		t1.start();
		t2.setNumber(10);
		t2.start();
	}
}
